package com.itheima.reggie.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录过滤器
 */

@WebFilter("/*")  //所有路径都要经过登录过滤器
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    //所有的请求都要走该过滤方法，该方法用来判断是否登录
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println(1);
        //将request和response转成http类型的
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();
        //System.out.println("LoginCheckFilter:==========获取请求路径开始=====================");
        //System.out.println("requestURI:"+requestURI);
        //System.out.println("LoginCheckFilter:==========获取请求路径结束=====================");

        //2、判断本次请求是否需要处理

        //不需要处理的路径：登录登出相关的controller，所有页面！
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/user/login",
                "/common/**", //放行文件上传下载的controller资源
                "/backend/**",
                "/front/**",
                "/user/login",
        };
        //举例：例如 /employee/save的路径就不会被认为跟登录登出相关的controller

        //3、如果不需要处理，则直接放行
        boolean check = check(urls, requestURI);
        if(check) {
            //System.out.println("LoginCheckFilter:我是跟登录无关的controller地址或者我是页面相关的资源，直接放行！");
            filterChain.doFilter(request,response);
            return;
        }
        //4、判断登录状态，如果已登录，则直接放行
        Long employeeID = (Long) request.getSession().getAttribute("employee");
        if(employeeID != null) {

            //向本地线程变量中存放当前用户的id
            BaseContext.setCurrentId(employeeID);
            //System.out.println("LoginCheckFilter:我已经是登录状态了，直接放行！");
            filterChain.doFilter(request,response);
            return;
        }

        Long userID = (Long) request.getSession().getAttribute("user");
        if(userID != null) {

            //向本地线程变量中存放当前用户的id
            BaseContext.setCurrentId(userID);
            //System.out.println("LoginCheckFilter:我已经是登录状态了，直接放行！");
            filterChain.doFilter(request,response);
            return;
        }


        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        //将R对象转成了一个JSON返回给前端页面，作为未登录的结果
        //System.out.println("LoginCheckFilter:我已经是跟登录无关的controller地址，返回未登录的JSON信息！");
        response.getWriter().write(new ObjectMapper().writeValueAsString(R.error("NOTLOGIN")));
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
